import os
from pathlib import Path
import ssl
from pathlib import Path
ssl._create_default_https_context = ssl._create_unverified_context
# 禁用SSL验证警告
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

os.environ['PYTHONHTTPSVERIFY'] = '0'

# 现有的BASE_DIR配置...
BASE_DIR = Path(__file__).resolve().parent.parent

# 构建项目内路径: BASE_DIR / 'subdir'
BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-2y#u%-6dgz*ikw&ksrm!89*vp9vjx5qj%@=onj4eyu2m^dr)g$'

# 安全警告: 生产环境中不要开启调试模式
DEBUG = True

# 允许的主机列表
ALLOWED_HOSTS = ['*']

# 量子密钥分发配置
QKD_KEY_LENGTH = 128           # 密钥长度
QKD_BATCH_SIZE = 10            # 量子比特批处理大小

# 应用定义
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sslserver',
    'my1',
    'qkd_app',
    'channels',
    'rest_framework',
    'rest_framework.authtoken',
]

# 跨域设置
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
ASGI_APPLICATION = 'djangoProject.asgi.application'

# 通道层配置
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels.layers.InMemoryChannelLayer',
    },
}

# 启用WhiteNoise
WHITENOISE_ENABLED = True

# 中间件配置
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # 静态文件处理
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# 根URL配置
ROOT_URLCONF = 'djangoProject.urls'

# 模板配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'my1/templates1'),
            os.path.join(BASE_DIR, 'my1/templates'),
            os.path.join(BASE_DIR, 'my1', 'templates1')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# WSGI应用配置
WSGI_APPLICATION = 'djangoProject.wsgi.application'

# 数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'manager',
        'HOST': '192.168.1.41',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
        'OPTIONS': {
            'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"',
            'charset': 'utf8mb4'
        }
    }
}

# REST框架配置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [],  # 关闭所有认证
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',  # 允许所有请求
    ]
}

# 密码验证设置
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# 国际化设置
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'  # 时区设置为上海
USE_I18N = True
USE_TZ = False  # 不使用时区

# 静态文件设置（CSS, JavaScript, 图片）
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

# 静态文件路径配置
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')  # 收集静态文件的绝对路径
STATICFILES_DIRS = [
     os.path.join(BASE_DIR, 'my1/static'),  # 原始静态文件目录
]

# DeepSeek API配置
DEEPSEEK_API_KEY = 'sk-302b312594814d0d80f45177777922c0'
DEEPSEEK_API_URL = "https://api.deepseek.com"

# 日志配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'qkd_debug.log',
            'formatter': 'verbose',
        },
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': True,
        },
        'qkd_app': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': 'INFO',
    }
}

# 默认主键字段类型
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# 会话设置
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

# ==================== HTTPS/SSL 配置 ====================

# SSL证书路径配置
SSL_CERTIFICATE = os.path.join(BASE_DIR, 'scertificate.crt')
SSL_KEY = os.path.join(BASE_DIR, 'sprivate.key')

# HTTPS安全设置
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False  # 开发环境设为False
CSRF_COOKIE_SECURE = False     # 开发环境设为False
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'SAMEORIGIN'

USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Cookie设置
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SAMESITE = 'Lax'

# 信任的来源（用于CSRF保护）
CSRF_TRUSTED_ORIGINS = [
    'https://localhost:8000',
    'https://127.0.0.1:8000',
    'https://10.19.32.31:8000',
    'https://192.168.1.41:8000'
    # 添加其他需要信任的域名
]
